﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Security.Cryptography;
using System.IO;
using System.Text;

/// <summary>
/// Summary description for RSA
/// </summary>

public class RSA_Session
{
   private RSACryptoServiceProvider _sp;

   const int keySize = 1024;

   public RSAParameters ExportParameters(bool includePrivateParameters)
   {
      return _sp.ExportParameters(includePrivateParameters);
   }

   public void GenerateKeys()
   {
      RSACryptoServiceProvider sp = new RSACryptoServiceProvider(keySize);
      System.Web.SessionState.HttpSessionState Session = HttpContext.Current.Session;

      string str = sp.ToXmlString(true);      
      Session["RSA_Private"] = str;

      str = sp.ToXmlString(false);
      Session["RSA_Public"] = str;
   }

   public void InitCrypto()
   {
      System.Web.SessionState.HttpSessionState Session = HttpContext.Current.Session;
      const int PROVIDER_RSA_FULL = 1;
      const string CONTAINER_NAME = "SpiderContainer";
      CspParameters cspParams;
      cspParams = new CspParameters(PROVIDER_RSA_FULL);
      cspParams.KeyContainerName = CONTAINER_NAME;
      cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
      cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; 
      // To avoid repeated costly key pair generation
      _sp = new RSACryptoServiceProvider(cspParams);
      var Key = Typecast.ToString(Session["RSA_Private"]);
      if (Key.Length < 1)
      {
         throw new ApplicationException("RSA keys not generated");
      }
      else
      {
         _sp.FromXmlString(Key);
      }
   }

   public byte[] Encrypt(string txt)
   {
      byte[] result;

      ASCIIEncoding enc = new ASCIIEncoding();
      int numOfChars = enc.GetByteCount(txt);
      byte[] tempArray = enc.GetBytes(txt);
      result = _sp.Encrypt(tempArray, false);

      return result;
   }

   public byte[] Decrypt(byte[] txt)
   {
      byte[] result;

      result = _sp.Decrypt(txt, false);

      return result;
   }

   public string DecryptToText(string txt)
   {
      return StringHelper.ASCIIBytesToString(StringHelper.FromBase64(StringHelper.ASCIIBytesToString(Decrypt(StringHelper.HexStringToBytes(txt)))));
   }

   public static string DecryptValue(string txt)
   {
      System.Web.SessionState.HttpSessionState Session = HttpContext.Current.Session;
      RSA_Session rsac = new RSA_Session();
      rsac.InitCrypto();

      return rsac.DecryptToText(txt);
   }
}